import * as qiniu from 'qiniu';
const bucket = 'jasen-resume'; //要上传的空间名
const imageUrl = 'https://resume.cjasen.com/'; // 空间绑定的域名
const accessKey = 'jFLQtv9Zk6z6_pHE7v-3iv3JZ_qP3sB7zzhnj78x'; //Access Key
const secretKey = 'FmkwiccCJX8oOdqyQJ8ir5KpMwlkGRPYDgnCVRiY'; //Secret Key
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
const config: any = new qiniu.conf.Config();
config.zone = qiniu.zone.Zone_z2;
config.useCdnDomain = true;
const formUploader = new qiniu.form_up.FormUploader(config);
class UploadQiniu {
  async upload(params) {
    const { filename, readableStream } = params;
    const imgSrc = await new Promise((resolve, reject) => {
      const putPolicy = new qiniu.rs.PutPolicy({
        scope: bucket + ':' + filename,
      });
      const uploadToken = putPolicy.uploadToken(mac);
      const timer = setTimeout(() => {
        this.putFile(uploadToken, filename, readableStream, resolve, reject);
        clearTimeout(timer);
      }, 1200);
      this.putFile(
        uploadToken,
        filename,
        readableStream,
        resolve,
        reject,
        timer,
      );
    });
    return imgSrc;
  }
  putFile(uploadToken, filename, readableStream, resolve, reject, timer?) {
    console.log('filename', filename);
    formUploader.putStream(
      uploadToken,
      filename,
      readableStream,
      null,
      (respErr, respBody, respInfo) => {
        timer && clearTimeout(timer);
        if (respErr) {
          reject(respInfo);
        }
        if (respInfo.statusCode == 200) {
          console.log('---', respBody);
          resolve(imageUrl + respBody.key);
        } else {
          reject(respInfo);
        }
      },
    );
  }
}
export default UploadQiniu;
